import React from "react";
import App from 'layout/App.js';
import "./index.less";
import Select from 'bee-select';
import 'bee-select/build/Select.css';
import {vendorsFmtDate as date, vendorsDanger as danger, vendorsGetStorage as getStorage, vendorsRemoveStorage as removeStorage} from "./../../utils/config";
import {queryProjectInfo, jumpPage, queryProjectInfoFromNcc  } from "./projectboard.config";
import {Breadcrumb } from 'tinper-bee';
class ProjectBoard extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            className :'a',
            count: 1,//一行能放几个
            data: new Array(1),
            num:1, //有几行,
            ceil :0,
            header:{
                'sname': { display : "项目名称：", },
                'scode': { display : "项目编码：", },
                'managerName': { display : "项目经理：", },
                'projectState': { display : "项目状态：", },
                'planStartDate': { display : "计划开始日期：", disable: true},
                'planEndDate': { display : "计划完成日期：", disable: true },
                'progress': { display : "子计划进度：", },
                'projectPlanVOS': { display : "子计划名称：", isSelectRef:true}
            },
            headerOrgin:{},
            selectData :[],
            selectedPk :'',
            pkProject :'',
            orginData :new Array(1),
            showBreadFlag : false
        };
    }
    componentDidMount (){
        let { pkProject } = getStorage("pkProject") ? getStorage("pkProject")  :{pkProject : ''};
        let { showBreadFlag } = getStorage("showBreadFlag") ? getStorage("showBreadFlag")  :{showBreadFlag : false};
        let searcharray = window.location.search.split('?')[1];
        let srcType = searcharray &&searcharray.length ?searcharray.split('&')[0] :[];
        let srcTypeArray = srcType && srcType.length ?srcType.split('=') :[];
       
        this.setState({
            pkProject,
            showBreadFlag
        }, ()=>{
            if(!srcTypeArray.length  &&!this.state.pkProject  || (srcTypeArray.length  && srcTypeArray[0]!=="pkSrc") ){
                return;
            }else{
                if(srcTypeArray[0] === "pkSrc" && srcTypeArray[1]){
                  
                    this.setState({
                        pkProject: srcTypeArray[1]
                    }, ()=>{
                        this.initncc()
                    })
                }else{
                    this.init() 
                }
            }
        })
    }
   
    componentWillUnmount (){
        removeStorage("pkProject")
    }
    //根据结果修改数据结构
    handleDataByRes = (res, pkPlan) =>{
        let {
            projectVO,
            millStoneProgs
        } = res;  
        let headerObj = Object.prototype.toString.call(projectVO) !== "[object Null]" ? this.handleHeaderStructor(projectVO) : this.state.header;
      
        let childPlanData = !pkPlan && this.handleChildPlanDataStructor(headerObj.projectPlanVOS.projectPlanVOS ? headerObj.projectPlanVOS.projectPlanVOS :[])

        this.setState({
            data: millStoneProgs ? [...millStoneProgs] : new Array(1),
            orginData: millStoneProgs ? [...millStoneProgs] : new Array(1),
            header : {...headerObj},
            headerOrgin: {...projectVO},
            selectData : pkPlan ? this.state.selectData : childPlanData.length ?  [...childPlanData] : new Array(1),
            selectedPk :  pkPlan ? this.state.selectedPk :  childPlanData[0] ? childPlanData[0].pkSchedule : '',
            pkProject : projectVO &&projectVO.pkProject ||''
        }, ()=>{
            this.handleBodyStruc()
        })
    }
    initncc = () =>{
        queryProjectInfoFromNcc({"pkSrc": this.state.pkProject, ieStamp :new Date().getTime(), isAjax:1} ).then((res)=>{
            if(res.data.resultCode !== "busi_ex"){
                this.handleDataByRes(res.data.result)
            }else{
                danger({text: res.data.exMsg})
            }
        })
    }
    init = (pkPlan) =>{
        queryProjectInfo({"projectId": this.state.pkProject, pkPlan, ieStamp :new Date().getTime(), isAjax:1} ).then((res)=>{
            if(res.data.resultCode !== "busi_ex"){
                this.handleDataByRes(res.data.result, pkPlan)
            }else{
                danger({text: res.data.exMsg})
            }
        })
    }

    handleBodyStruc = () =>{
        let width =document.getElementsByClassName("row")[0] && document.getElementsByClassName("row")[0].clientWidth ||1000
        let widthOfItem = document.getElementsByClassName("item")[0]&& document.getElementsByClassName("item")[0].offsetWidth || 300;  
        let count =  Math.floor(width/widthOfItem);//一行能放下的个数
        let ceil =  count - this.state.orginData.length % count;//需要补充的classname为item的空白div的个数
        let num =  Math.ceil(this.state.orginData.length/count);//放几行
     
        this.setState({
            num,
            count :count ,
            ceil
        }, ()=>{
            this.setState({
                data : this.state.orginData.concat(new Array(this.state.ceil))
            })
        })
    }

    getMillstonesByPkplan = (item, callback) =>{
        let _self = this;
        let pkPlan = ''
        if(item){
            pkPlan = item;
        }else{
            pkPlan = _self.state.selectedPk;
        }
        if(!_self.state.pkProject){
            return;
        }else{
            _self.init(pkPlan)
        }      
        
    }
    

    handleChildPlanDataStructor = (data)=>{
        data.map((item, index)=>{
            Object.assign(item, {"key": item.name}, {value: item.pkSchedule})
        })
        return data
    }

    handleHeaderStructor = (header) =>{
        let obj = this.state.header;
        Object.keys(header).map((item, index)=>{
            switch(item){
         
                case "planStartDate" :
                case "planEndDate" :
                    obj[item][item] = date(Object.values(header)[index])
                    return;
                break;
                case "projectPlanVOS" :
                    obj[item].isSelectRef = true;
                break;
                case "projectState" :
                    let projectState = this.getState(Object.values(header)[index]);
                    obj[item][item] =projectState
					return 
                case "managerName" :
                case "scode" :
                case "sname" :
                    break;
                case "progress" :
                    obj[item][item] =`${Object.values(header)[index]}%`;
                    return;
                break
                default :
                return;
                break;
            }
            obj[item][item] = Object.values(header)[index]
        })
        return obj;
    }


    getState = (rec) => {
        let projectState = rec;
        
		switch (rec) {
            case -1:
                projectState = '创建';
                break;
            case 0:
                projectState = '施工中';
                break;
            case 1:
                projectState = '竣工';
                break;
            case -2:
                projectState = '暂停';
                break;
            case -3:
                projectState = '停工';
                break;
            case 3:
                projectState = '复工';
                break;
        }

		return projectState
	};

    jumpPage = (item) => {
       
        if(!item.relatedBillType){
            return ;
        }
        let crossOrigin = window.location.search && window.location.search.split("crossOrigin") ||[];
        let flag  =crossOrigin.length && crossOrigin[1] && crossOrigin[1].split("=").length && crossOrigin[1].split("=")[1] ? true : false;
        if(flag && item.isNcBill){//ncc
            
            jumpPage({'billtype' : item.relatedBillType, ieStamp :new Date().getTime(), isAjax:1} ).then((res)=>{
                if(res.data.resultCode !== "busi_ex"){
                    let data = res.data.result;
            
                    if(Object.keys(data).length){
                        let mainUrl =   crossOrigin[1].split("=")[1] + "#/ifr?"; //首页地址
                        let preffix = mainUrl.includes("/nccloud/resources");
                        let pageParam = "ifr=" + encodeURIComponent(encodeURIComponent(`${preffix? data.pageurl : '/nccloud/resources'+data.pageurl}?status=browse&id=${item.relatedPkBill}`)); //页面地址参数
                        let sysParam = `&c=${encodeURIComponent(encodeURIComponent(data.appcode))}`+  //appcode
                                    `&p=${encodeURIComponent(encodeURIComponent(data.pagecode))}`+  //pagecode
                                    `&ar=${encodeURIComponent(encodeURIComponent(''))}`+  //应用id
                                    `&n=${encodeURIComponent(encodeURIComponent(data.name))}`    // +应用名称
                                
                        let targetUrl = mainUrl + pageParam + sysParam;
    
                        window.open(targetUrl);
                    }
                   
                }else{
                    danger({text: res.data.exMsg})
                }
            })
          
        }else if(!item.isNcBill){ //友工程

            let params = {
                pk_org: this.state.headerOrgin.pkOrg,
                orgName: this.state.headerOrgin.orgName,
                billType: item.relatedBillType,
                pkProject: item.pkProject,
                projectName: item.projectName,
                showBreadcrumb: 4,
                
            };

            let searcharray = window.location.search.split('?')[1];
            let srcType = searcharray &&searcharray.length ?searcharray.split('&')[0] :[];
            let srcTypeArray = srcType && srcType.length ?srcType.split('=') :[];

            sessionStorage.setItem('fromGroupData', JSON.stringify(params));
            document.cookie = `tenantid=${item.pkTenant}`;

            if(srcTypeArray[0] === "pkSrc" && srcTypeArray[1]){
                window.location.href=`billsInquiry.html?pkSrc=${srcTypeArray[1]}`
            }else{
                window.location.href="billsInquiry.html?page_state=1"
            }
           
           
        }
        
    }

    //里程碑区域的每一项
    showContentByStatus = (item) =>{
        let _self = this;
        let text = ('')
        switch (item.milestoneStatus){
            case "已完成" : text = (
                <div className = {'item-item'}>
                    <div style={{ display: 'flex', alignItems: 'center',}}>
                        <div className = {'status'} style={{background : "#F0F0F0"}} >已完成</div>
                        <div style={{height: 20, width:20, marginLeft:"-9", transform:"rotate(45deg)", background:'#F0F0F0'}}></div>
                    </div>
                    <div className ={"milestones-name"}>
                        {item.isExtension ? <div className ={"delay"}>[延期]</div> : null}
                        <div style={{color: item.isNcBill || item.relatedBillType ? "#007BFF" :'#101010'}} onClick={()=>_self.jumpPage(item)}>
                            {item.milestoneName}
                        </div>
                    </div>
                    <div className={'date'}>
                        <div>实际开始日期 ：{date(item.progressVO && item.progressVO.startDate)}</div>
                        <div>实际完成日期 ：{date(item.progressVO&&item.progressVO.endDate)}</div>
                    </div>
                    <div className={"greyCircle"}></div>
                </div>
            )
            break;
            case "进行中" :text = (
                <div  className = {'item-item'}>
                    <div style={{    display: 'flex', alignItems: 'center',}}>
                        <div  className = {'status'} style={{background : "#D4F4D4"}} >进行中</div>
                        <div style={{height: 20, width:20, marginLeft:"-9", transform:"rotate(45deg)", background:'#D4F4D4'}}></div>
                    </div>
                    <div  className ={"milestones-name"}>
                        {item.isExtension ? <div style={{color:'red'}}>[延期]</div> : null}
                        <div style={{color: item.isNcBill || item.relatedBillType ? "#007BFF" :'#101010'}}>{item.milestoneName}</div>
                    </div>
                    <div className={'date'}>
                        <div>里程碑进度 ：{item.progressVO&&item.progressVO.progress} %</div>
                        <div>计划完成日期 ：{date(item.planEndDate)}</div>
                    </div>
                    <div className={"greyCircle"}></div>
                </div>
            )
            break;
            case "未开始" :text = (
                <div  className = {'item-item'}>
                    <div style={{    display: 'flex', alignItems: 'center',}}>
                        <div  className = {'status'} style={{background : "#E0EFFF"}}>未开始</div>
                        <div style={{height: 20, width:20, marginLeft:"-9", transform:"rotate(45deg)", background:'#E0EFFF'}}></div>
                    </div>
                    <div  className ={"milestones-name"}>
                        {item.isExtension ? <div style={{color:'red'}}>[延期]</div> : null}
                        <div style={{color: item.isNcBill || item.relatedBillType ? "#007BFF" :'#101010'}}>{item.milestoneName}</div>
                    </div>
                    <div className={'date'}>
                        <div>计划开始日期 ：{date(item.planStartDate)}</div>
                        <div>计划完成日期 ：{date(item.planEndDate)}</div>
                    </div>
                    <div className={"greyCircle"}></div>
                </div>
            )
            break;
           
        }
        return text;
    }

    //里程碑区域每一行
    content = ()=>{
        let _me = this;
        let dataAll =[... _me.state.data];
        let count =_me.state.count;
        let num =_me.state.num;
        var res = [];
            for(let i = 0; i < num; i++) {
                let data = dataAll.slice( (i) * (count), (1+i)*count)
                res.push(
                    <div 
                        className={"row" } 
                        style={{borderRight:  (i !== 0 )&& (i % 2 == 1) ? "1px solid #bbb" :'0' , borderLeft : i!== 0&& (i % 2 == 0)  ? "1px solid #bbb" : '0', flexDirection: i % 2 ==0 ? "row" :'row-reverse',justifyContent: data.length === count ? "space-around" :''}}
                    >
                        {
                            dataAll.length 
                                ?  
                                data.map((item, index)=>{
                                    return(
                                        <div className = {"item"}  >
                                            { item ? this.showContentByStatus(item) : null}
                                        </div>
                                    )
                                }):
    
                                <div className={"item"}></div>
                        }
                    </div>
                  )
            }
            return res
    }

    handleSelectChange = (selectValuePk, selectValue) =>{
        this.setState({
            selectedPk :selectValuePk
        }, () =>{
            this.getMillstonesByPkplan(selectValuePk)
        })
    }

    //头部
    header = () =>{
        let _self = this;
        let header = _self.state.header;
        let res = [];
        Object.keys(header).map((item, index)=>{
            !Object.values(header)[index].disable &&
                res.push(
                    <div className = {"headerItem"}>
                        {
                            Object.values(header)[index].isSelectRef? 
                            <div className = {'selectDiv'}>
                                { Object.values(header)[index].display }
                                    
                                <Select
                                    onChange={_self.handleSelectChange}
                                    placeholder={'请选择'}
                                    notFoundContent="没有相关条目"
                                    className={"planSelect"}
                                    defaultValue = {_self.state.selectedPk}
                                    value = {_self.state.selectedPk}
                                    data={_self.state.selectData}
                                />
                            </div>
                        :
                            <div>
                                { Object.values(header)[index].display }
                                { Object.values(header)[index][item]}
                            </div>
                        }
                    
                    </div>
            )
        })
       
        return res;
    }
    render() {
        let _self = this;
        window.onresize = function(){
            _self.handleBodyStruc();//页面布局实时变动
        }
        return (
            <App >
                <div  className="container">
                    <div className="bill-header padding-left10">
                        {_self.state.showBreadFlag ?
                            <div className="brc-nav">
                                <Breadcrumb>
                                    <Breadcrumb.Item href='/workfile.html' style={{color :'#1115ff'}}>
                                        项目档案
                                    </Breadcrumb.Item>
                                    <Breadcrumb.Item active>
                                        进度看板
                                    </Breadcrumb.Item>
                                </Breadcrumb>
                            </div> : null}
                    </div>
                    <div className="header">
                        <div className="title">
                            进度看板
                        </div>
                        <div className="content">
                            {_self.header()}
                        </div>
                    </div>
                    <div className={"middle"}>
                        <div className="title">
                            里程碑
                        </div>
                        <div className="content" >
                            {_self.content()}
                        </div>
                    </div>
                </div>
            </App>
        );
    }
}

export default ProjectBoard;
